from enum import Enum

from aiohttp import ClientSession


class ResponseTypes(Enum):
    JSON: str = "json"
    XML: str = "xml"


class Interval(Enum):
    H1: int = 60
    D1: int = 24


class AsyncMoexBase:
    def __init__(self, response_type: ResponseTypes = ResponseTypes.JSON):
        self.base_url = "https://iss.moex.com/iss/"
        self.response_type = response_type

    def _generate_url(self, url: str, query_params: dict | None) -> str:
        url = f"{self.base_url}{url}.{self.response_type.value}"
        if query_params:
            query_params_list = []
            for param, value in query_params.items():
                query_params_list.append(f"{param}={value}")
            url += "?" + "&".join(query_params_list)
        return url

    async def _make_request(self, url: str, query_params: dict = None) -> dict:
        async with ClientSession() as session:
            request_url = self._generate_url(url, query_params)
            print(request_url)
            async with session.get(request_url) as resp:
                return await resp.json()

    async def _make_multi_requests(self, base_key: str, url: str, query_params: dict = None):
        start = 0
        limit = 100
        _query_params = {
            "start": start,
            "limit": limit,
        }
        if query_params:
            _query_params = {
                **_query_params,
                **query_params,
            }
        response = await self._make_request(
            url,
            _query_params,
        )
        result = {**response}
        start += limit
        while len(response[base_key].get("data", [])) == limit:
            _query_params["start"] = start
            response = await self._make_request(
                url,
                _query_params,
            )
            result[base_key]["data"] = [
                *response[base_key]["data"],
                *result[base_key]["data"],
            ]
            start += limit

        return result

    def _parse_list(self, response_data: dict) -> list[dict]:
        metadata = response_data.get("metadata", [])
        columns = response_data.get("columns", [])
        data = response_data.get("data", [])

        result = []
        for item in data:
            row = {}
            for index, column in enumerate(columns):
                row[column] = item[index]
            result.append(row)

        return result
